import React, { useState } from 'react';
import { Modal, View, Text, ActivityIndicator, StyleSheet } from 'react-native';

let loadingInstance: any = null;

const LoadingOverlay = () => {
  const [visible, setVisible] = useState(false);
  const [message, setMessage] = useState('');

  const show = (msg = '加载中...') => {
    setMessage(msg);
    setVisible(true);
  };

  const hide = () => {
    setVisible(false);
    setMessage('');
  };

  loadingInstance = { show, hide };

  return (
    <Modal
      transparent={true}
      visible={visible}
      animationType="fade"
      onRequestClose={() => hide()} // Android返回按钮关闭
    >
      <View style={styles.overlay}>
        <View style={styles.container}>
          <ActivityIndicator size="large" color="#fff" />
          <Text style={styles.message}>{message}</Text>
        </View>
      </View>
    </Modal>
  );
};

// 全局函数用于调取组件的实例
export const Loading = {
  show: (msg: string = '加载中...') => {
    if (loadingInstance) {
      loadingInstance.show(msg);
    }
  },
  hide: () => {
    if (loadingInstance) {
      loadingInstance.hide();
    }
  },
};

const styles = StyleSheet.create({
  overlay: { flex: 1, justifyContent: 'center', alignItems: 'center' },
  container: { width: 150, height: 120, backgroundColor: '#333', borderRadius: 10, justifyContent: 'center', alignItems: 'center', padding: 20 },
  message: { color: '#fff', marginTop: 10, fontSize: 16, textAlign: 'center' },
});

export default LoadingOverlay;
